const article = require('express').Router()
const body = require('body-parser')
const { Article } = require('../../mongoDB/mongoDB')
const fs = require('fs')
const path = require('path')
const promisify=require('util').promisify;
const readFile=promisify(fs.readFile);

article.use(body.urlencoded({extended: false}))
article.post('/article', async (req, res) => {
	const data = JSON.parse(Object.keys(req.body)[0])
	const articleNum = await Article.find()
	const random = Math.floor(Math.random()*1500 +500)
	const importance = Math.floor(Math.random()*3+1)
	data.serialNumber = articleNum.length
	data.readings = random
	data.importance = importance
	Article.create(data)
	const response = await Article.find(data)
	res.send(response)
})
article.get('/article', async (req, res) => {
	const paramObj = {}
	for(let key in req.query) {
		if(req.query[key] !== '' && req.query[key] !== undefined) {
			paramObj[key] = req.query[key]
		}
	}
	if(paramObj.method === 'false') {
		let filePath = ''
		if(paramObj.category == 'true') {
		  filePath = path.join(__dirname, '..', '..', 'mongodbData', 'articles.json')
		}else {
  		  filePath = path.join(__dirname, '..', '..', 'mongodbData', 'createarticles.json')
		}
		const result = await readFile(filePath, 'utf8')
		let r = JSON.parse(result)
		if(paramObj.category == 'true') {
			r = r.filter(item => {
				return item.country == paramObj.country
			})
		}
		res.send({response: r})
		return
	}else {
		console.log(0)
		const params = Object.keys(paramObj)
		let reg = undefined
		if(params.includes('content')) {
			reg = new RegExp(paramObj.content + "+", "gi")
		}
		let response = undefined
		let queryParams = {}
		if(params.length === 2) {
			queryParams = {}
		}else {
			if(params.includes('content') && params.length === 4) {
				if(params.includes('importance')) {
					queryParams = {
						title: reg,
						importance: paramObj.importance
					}
				}else{
					queryParams = {
						title: reg,
						country: paramObj.country
					}
				}
			}else if(params.includes('content') && params.length === 5) {
				queryParams = {
					title: reg,
					importance: paramObj.importance,
					country: paramObj.country
				}
			}else if(params.length === 4){
				queryParams = {
					importance: paramObj.importance,
					country: paramObj.country
				}
			}else if(params.length === 3) {
				if(params.includes('content')) {
					queryParams = {
						title: reg
					}
				}else if(params.includes('country')){
					queryParams = {
						country: paramObj.country
					}
				}else if(params.includes('importance')){
					queryParams = {
						importance: paramObj.importance
					}
				}
			}
		}
		response = await Article.find(queryParams).skip((paramObj.currentPage -1)*(paramObj.currentNum - 0)).limit(paramObj.currentNum - 0).sort('serialNumber')
		const back = {
			total: (await Article.find(queryParams)).length,
			response
		}
		res.send(back)
	}
})
article.put('/article/:id', async (req, res) => {
	const serialNumber = req.params.id
	const p = JSON.parse(Object.keys(req.body))
	const response = await Article.findOne({serialNumber})
	if(p.length === 1 && response) {
		const obj = p.status
		const result = await Article.updateOne({serialNumber}, {status})
		res.send(result)
		return
	}else {
		const obj = p
		const result = await Article.updateOne({serialNumber}, obj)
		res.send(result)
	}
	res.send('Ok')
})

article.delete('/article/:id', async (req, res) => {
	const serialNumber = req.params.id
	const response = await Article.deleteOne({serialNumber})
	res.send(response)
})
module.exports = article